package com.huzz.service.impl;

import com.huzz.entity.SysRole;
import com.huzz.entity.SysUser;
import com.huzz.mapper.RoleMapper;
import com.huzz.mapper.UserMapper;
import com.huzz.service.CustUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 登录用户信息构建
 *
 * @author Huzz
 * @create 2022-08-18 12:13
 */
@Service
@Transactional
public class CustUserDetailServiceImpl implements CustUserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名去数据库中查询指定用户，这就要保证数据库中的用户的名称必须唯一，否则将会报错
        SysUser sysUser = userMapper.findByUsername(username);
        //如果没有查询到这个用户，说明数据库中不存在此用户，认证失败，此时需要抛出用户账户不存在
        if (sysUser == null) {
            throw new UsernameNotFoundException("user not exist.");
        }

        //存放权限的
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色
        List<SysRole> roles =roleMapper.findByUid(sysUser.getId());
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
            // 权限
            // List<Permission> permissionList=permissionMapper.selectByRoleId(role.getId());
            // for (Permission permission:permissionList){
            //     //添加到
            //     authorities.add(new SimpleGrantedAuthority(permission.getName()));
            // }
        }
        sysUser.setAuthorities(authorities);

        return sysUser;
    }
}
